package com.liqy.huoshan.api.net;

import com.ihsanbal.logging.Level;
import com.ihsanbal.logging.LoggingInterceptor;
import com.liqy.huoshan.BuildConfig;
import com.liqy.huoshan.api.HuoShanApi;
import com.liqy.huoshan.api.SnsApi;
import com.liqy.huoshan.api.net.interceptor.HttpCommonParamsInterceptor;
import com.liqy.huoshan.api.net.param.QueryParam;
import com.liqy.huoshan.util.ObjectUtils;

import java.util.Map;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.liqy.huoshan.api.HsConstants.API_HOST;

/**
 * 附上参考链接
 * 网路请求封装除了考虑单例模式：
 * http://www.importnew.com/18872.html
 * http://blog.csdn.net/jason0539/article/details/23297037/
 * ，还需要考虑以下几个方面
 * URL 参数化封装 动态URL封装：https://www.v2ex.com/t/378157
 * 公共参数封装：https://github.com/leepood/okhttp-common-params-interceptor
 * 日志拦截器：https://github.com/ihsanbal/LoggingInterceptor
 * 缓存拦截器：https://github.com/xiaolei123/OkhttpCacheInterceptor
 * RxJava 数据处理封装：https://github.com/0xm1nam0/RxCore
 * 数据处理异常封装
 * 取消订阅，和生命周期方法绑定处理：https://github.com/trello/RxLifecycle
 * 网路中断处理
 * Created by liqy on 2017/12/26.
 */

public class RetrofitHelper {

    private static Retrofit retrofit;

    static {
        initRetrofit(API_HOST);
    }

    /**
     * 获取OkHttpClient
     *
     * @return
     */
    private static OkHttpClient getOkHttpClient() {

        //TODO 处理拦截器，自定义缓存，HTTP的一些参数设置
        OkHttpClient.Builder builder = RetrofitUrlManager
                .getInstance()
                .with(new OkHttpClient.Builder()) //RetrofitUrlManager 初始化
//                .readTimeout(30, TimeUnit.SECONDS)
//                .connectTimeout(30, TimeUnit.SECONDS)
                ;


        //只有再开发版本才打印log日志
        if (BuildConfig.DEBUG) {
            //TODO 日志拦截器
            builder.addInterceptor(new LoggingInterceptor.Builder()
                    .loggable(BuildConfig.DEBUG)
                    .setLevel(Level.BASIC)
                    .log(Platform.INFO)
                    .tag("huoshan")
                    .request("Request")
                    .response("Response")
                    .addHeader("version", BuildConfig.VERSION_NAME)
                    .build());
        }

        try {
            Map<String, String> map = ObjectUtils.objectToMap(new QueryParam());
            HttpCommonParamsInterceptor commonParamsInterceptor = new HttpCommonParamsInterceptor.Builder()
                    .type(HttpCommonParamsInterceptor.Builder.Type.QUERY_STRING)
                    .params(map)
                    .build();
            builder.addInterceptor(commonParamsInterceptor);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return builder.build();
    }

    /**
     * 初始化Retrofit
     *
     * @param url
     */
    private static void initRetrofit(String url) {
        if (retrofit == null) {
            synchronized (Retrofit.class) {
                if (retrofit == null) {
                    retrofit = new Retrofit.Builder()
                            .baseUrl(url)
                            .client(getOkHttpClient())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }
    }

    public static HuoShanApi getHuoShanAPI() {
        return createAPI(HuoShanApi.class);
    }

    public static SnsApi getSNSAPI() {
        return createAPI(SnsApi.class);
    }

    private static <T> T createAPI(Class<T> clzss) {
        return retrofit.create(clzss);
    }

}
